<?php
namespace control;

/*
*物资领用类
*/

class materialOutClass extends adIndexClass
{
    private const page = 'materialOut';
    private const table = 'stock';
    private const tableMx = 'stock_detail';
    private const title = '物资领用记录';
    public array $stateOption = ['制单', '审核中','已通过','待出库','已出库'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => "领用单号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'receivingStid' => [
                        'name'  => "领用人",
                        'width' => 300,
                    ],
                    'deptName'  => [
                        'name'  => "领用人部门",
                        'width' => 300,
                    ],
                    'stid'         => [
                        'name'  => '制单人',
                        'width' => 200,
                    ],
                    'recordDate'          => [
                        'name'  => '领用日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'    => [
                        'name'  => '状态',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "领用单号" => text(array("name" => "orderNo")),
                    "领用人"     => selectMultiple(array("name" => "receivingStid",'table'=>'staff',"sqlId"=>'stid','sqlField'=>'name','class'=>'width200')),
                    '领用人部门' => selectMultiple(array("name" => "department",'table'=>'department',"sqlId"=>'name','sqlField'=>'name','class'=>'width200')),
                ],
                [
                    '制单人'   => selectMultiple(array("name" => "stid",'table'=>'staff',"sqlId"=>'stid','sqlField'=>'name','class'=>'width200')),
                    "领用日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    '状态'   => select(array("name" => "state", "option" => $this->stateOption)),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//编码
            "deptName" => $this->post('department'),//规格
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "type" => '出库',//类型
        );
        $and = $this->seeSelf(self::page,'receivingStid');
        if ($this->post('createTime')) {
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and recordDate >='{$timeArr[0]}' and recordDate <='{$timeArr[1]}'";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "receivingStid":
                    case "stid":
                        $row[] = self::findStaff($array[$key]);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id')?:self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $where = "1=1 ".$this->seeSelf(self::page)?:'1=1';
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . "领用人：" => selectMultiple(["name" => "receivingStid",'title'=>'领用人','table'=>"staff",'where'=>$where,'sqlId'=>'stid','sqlField'=>'name', "value" => $info['receivingStid']]),
                    must . "领用日期：" => text(["name" => "recordDate", 'laydate'=>[],'class' => 'text', "value" => $info['recordDate']]),
                ],
                [
                    "备注：" => textarea(["name" => "text",  'class' => 'textarea', "value" => $info['text']]),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 250, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'receivingStid' => $this->post('receivingStid'),
            'recordDate' => $this->post('recordDate'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'receivingStid' => '领用人',
            'recordDate' => '领用日期',
        ];
        $rules = [
            'receivingStid' => 'required',
            'recordDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            $staff = query('staff'," stid = '$field[receivingStid]'");
            $job = query('job'," id = '$staff[jobId]'");
            $department = query('department'," id = '$job[departmentId]'");
            $field['deptName'] = $department['name'];
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'QSOU'.date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'type'=>'出库',
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '制单',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }
    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button=[];
        if ($info['state'] == '制单' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name'=>'物资领用',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],

                        //执行发起时验证函数
                        'before' => [

                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'],  'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['制单', '待出库'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'],'cancel') && $info['state'] != '制单' && $info['state'] != '已出库') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                 "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['制单'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );

            $button = [];
            $mxButton='';
            if ($this->power(self::page, "edit") && $info['state'] =='制单') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];
                $mxButton = "<span class='smallButton' onclick=\"layer('" . self::page . "','addMx',{id:'" . $info['id'] . "'})\">选择物资</span>
<span class='smallButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delMx'})\">移除</span>";
            }
            if ($this->power(self::page, "del") && $info['state'] =='制单') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "confirm") && $info['state'] =='待出库'){
                $button[] = [
                    "name" => "确认出库",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);

            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
            $checkAll = $this->checkAll("detailForm", "mxId");
            $tr[] = [$checkAll, '编码', '品名', '规格', '单位', '仓库名称','库存数量','领用数量', '备注'];
            $totalArr = ['stock'=>0,'num'=>0];
            foreach ($result['array'] as $val) {
                //列表控件
                $dominate = array(
                    "box" => array("name" => "mxId", "value" => $val['id']),
                );
                $material = query('resource', " id = '$val[materialId]'");
                //库存
                $stockNum = find(array('table'=>"stock_record","where"=>" materialId = '$val[materialId]' and warehouse = '$val[warehouse]'",'sum'=>"num"));
                //占有库存但还未出库的单子
                $outNum = find(array('table'=>'stock_detail as a join stock as b on a.orderId = b.id','where'=>" a.materialId = '$val[materialId]' and a.warehouse = '$val[warehouse]' and b.state in ('审核中','已通过','待出库') and b.id !='$info[id]'",'sum'=>"num"));
                $stock = $stockNum-$outNum;
                if ($info['state'] =='制单'){
                    $tr[] = [$this->dominate($dominate), $material['code'], $material['name'], $material['model'], $material['unit'],$val['warehouse'],self::lostZero($stock,'numPrecision'),text(array('name'=>'num[]','class'=>'text textPrice','blur'=>'setVal', 'other' => self::digitalFiltering('numPrecision'),'value'=>$val['num']?self::lostZero($val['num'],'numPrecision'):''))
                        ,text(array('name'=>'text[]','class'=>'select','blur'=>'setVal','value'=>$val['text']))];
                }else{
                    $tr[] = [
                        '',
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $material['unit'],
                        $val['warehouse'],
                        self::lostZero($stock,'numPrecision'),
                        self::lostZero($val['num'],'numPrecision'),
                        $val['text']
                    ];
                }
                $totalArr['stock'] += $stock;
                $totalArr['num'] += $val['num'];

            }
            $total_tr = [
                6 => "<span class='totalNum'>".self::lostZero($totalArr['stock'], 'numPrecision')."</span>",
                7 => "<span class='totalNum'>".self::lostZero($totalArr['num'], 'numPrecision')."</span>",
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "领用单号" => $info['orderNo'],
                        "领用人部门" => $info['deptName'],
                        "领用人" => self::findStaff($info['receivingStid']),
                        "领用日期" =>  $info['recordDate'],
                    ),
                    array(
                        "制单人" =>self::findStaff($info['stid']),
                        "制单时间" => $info['time'],
                        "确认时间" => self::null($info['confirmTime']),
                        "状态" => $info['state'],
                    ),
                    array(

                        "备注" => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '选择明细',
                'button' => $mxButton,
                'html' => "
                <div class='purchaseMx'>
                    <form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->listTable(array('tr' => $tr, 'total' => $total_tr, 'showSort' => true)) . "</form>
                </div>
                ",
            ]);
            $data['html'] .= $this->detailBlock([
                '流程' => auditClass::auditRecord(self::table,$info['id'])
            ]);
            $data['html'] .= <<<efot
<script>
function setVal(e){
    let id = $(e).parent().parent().find("[name='mxId[]']").val();
    let num = $(e).parent().parent().find("[name='num[]']").val();
    let text = $(e).parent().parent().find("[name='text[]']").val();
    $.post(root+"control/adIndex.html?cla={$this->get('cla')}&fun=setVal",{id:id,num:num,text:text},function (res){
        if (res.warn !==2){
            warn(res.warn);
        }
        $('.totalNum').text(pageEditTotal(".purchaseMx", "[name='num[]']"))
    },'json')

}
</script>


efot;

            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 填写领用明细
     */
    public function setVal(){
        $field = array(
            'num'=>self::formattingFigure($this->post('num'),'numPrecision'),
            'text'=>$this->post('text'),
        );
        $mx = query(self::tableMx," id = '{$this->post('id')}'");
        $info = query(self::table," id = '$mx[orderId]'");
        //库存数量
        $stockNum = find(array('table'=>'stock_record','single'=>" materialId = '$mx[materialId]'",'sum'=>"num"));
        //占有库存但还未出库的单子
        $outNum = find(array('table'=>'stock_detail as a join stock as b on a.orderId = b.id','where'=>" a.materialId = '$mx[materialId]' and a.warehouse = '$mx[warehouse]' and b.state in ('审核中','已通过','待出库') and b.id !='$mx[orderId]'",'sum'=>"num"));

        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        }elseif(empty($mx['id'])){
            $json['warn'] = '未找到此明细';
        }elseif($info['state'] !='制单'){
            $json['warn']= '此订单不是制单状态，不能修改';
        }elseif(($stockNum-$outNum) < $field['num']){
            $json['warn'] = '库存数量不足，此物资剩余库存数量：'.($stockNum-$outNum);
        } else {
            $json['warn'] = static::update([
                "table" => self::tableMx,
                "field" => $field,
                "where" => " id = '$mx[id]'"
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了物资领用明细 id：【" . $mx['id'] . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                $json['warn'] = 2;
            }
        }
        resp:
        return json_encode($json, 320);

    }
    /**
     * 添加明细
     * @return bool|string
     */
    public function addMx()
    {
        $html =
            text(array("name" => "name", "title" => "品名")) .
            text(array("name" => "code", "title" => "编码")) .
            text(array("name" => "model",  "title" => "规格")) .
            select(array("name" => "type", 'option'=>explode('，',para('materialType')), "title" => "类别")) .
            hidden(array('name' => 'id', 'value' => $this->post('id')));
        $button = "<input style='margin-left: 5px' onclick=\"subForm('mxForm', '" . root . "control/adIndex.html?cla=" . self::page . "&fun=addMxEdit');\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 500, "html" => $html, "button" => $button));
    }

    /**
     *添加明细
     */
    public function addMxSearch()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $and = '1=1';
        $like = [
            'name' => $this->post('name'),
            'code' => $this->post('code'),
            'model' => $this->post('model'),
        ];
        $equal = [
            'type' => $this->post('type'),
        ];
        $mAnd = search(["like" => $like, "=" => $equal]);
        if ($mAnd){
            $and.=" and materialId in (select id from resource where 1=1 {$mAnd})";
        }
        $where = $and." group by materialId,warehouse";
        $page = $this->page([
            'field'=>"any_value(materialId) as materialId,any_value(warehouse) as warehouse,any_value(id) as id,sum(any_value(num)) as num",
            "table" => " stock_record",
            "where" => $where,
            'pageNum' => 50,
            "order" => "",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, '仓库名称','类别', '编码', '品名', '规格', '单位', '库存数量'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            //$warehouse = query('warehouse'," id = '$array[warehouse]'");
            $material= query('resource'," id = '$array[materialId]'");
            //占有库存但还未出库的单子
            $outNum = find(array('table'=>'stock_detail as a join stock as b on a.orderId = b.id','where'=>" a.materialId = '$array[materialId]' and a.warehouse = '$array[warehouse]' and b.state in ('审核中','已通过','待出库') and b.id !='$info[id]'",'sum'=>"num"));

            $tr[] = array(
                $this->dominate($dominate),
                $array['warehouse'],
                $material['type'],
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                self::lostZero($array['num']-$outNum,'numPrecision'),
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                hidden(array('name' => 'id', 'value' => $id)) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * 添加
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id = $this->post('id');
        $mxIdArr = $this->post('mxId');
        $info = query(self::table, " id = '{$this->post('id')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择物资';
        } else {
            $x = 0;
            foreach ($mxIdArr as $mxId) {
                $stockRecord= query('stock_record', " id = '$mxId'");
                $material= query('resource', " id = '$stockRecord[materialId]'");
                $mx = query(self::tableMx, " materialId = '$mxId' and orderId = '$id'");
                if (!$mx['id']) {
                    //未在明细中
                    $warn = insert(array(
                        'table' => self::tableMx,
                        'field' => [
                            'id' => suiji(),
                            'orderId' => $id,
                            'materialId' =>$material['id'],
                            'warehouse' =>$stockRecord['warehouse'],
                            'unit' => $material['unit'],
                            'time' => $this->time
                        ]
                    ));
                    if ($warn == '新增成功') {
                        $x++;
                        $text = $this->control['name'] . "添加了物资【{$material['name']}】到领用单【{$info['orderNo']}】中";
                        $this->logText(array("type" => self::page, "text" => $text));
                    }
                }
            }
            $json['warn'] = 2;
            $_SESSION['warn'] = '添加了' . $x . '条物资到领用单中';
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power=$word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认出库？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'delMx':
                $act = 'del';
                $msg = '删除明细';
                $title = self::page . 'DeleteMx';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }
    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已出库',
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此领用申请';
        } elseif ($info['state'] != '待出库') {
            $json['warn'] = '此领料单不是待出库状态，不能确认';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->insertInventory($info);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 出库记录
     * @param $info
     */
    public function insertInventory($info)
    {
        $all = find(array('table'=>'stock_detail',"where"=>" orderId = '$info[id]'"));
        foreach ($all['array'] as $array){
            insert(array(
                'table'=>'stock_record',
                'field'=>[
                    'id'=>self::getId(),
                    'type'=>'出库单',
                    'sourceTable'=>'stock_detail',
                    'sourceId'=>$array['id'],
                    'num'=>-$array['num'],
                    'price'=>$array['price'],
                    'warehouse'=>$array['warehouse'],
                    'materialId'=>$array['materialId'],
                    'time'=>$this->time,
                ]
            ));
        }
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '制单') {
                    $warn = "不是制单状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除明细
     * @return bool|string
     */
    public function deleteMx()
    {
        $array = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                $info = query(self::table, " id = '$mx[orderId]' ");
                $material= query('resource', " id = '$mx[materialId]' ");
                if ($info['state'] !='制单'){
                    $warn = "删除失败：不是制单状态";
                }else{
                    //最后删除基本参数
                    delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;

                }
                $text .= "物资【{$material['name']}】,ID【" . $mx['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了领用明细，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个领用明细，详情见系统日志。";
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }
}

